package com.hwpt.hwaccount.core.utils;

import android.util.Log;

import com.hwpt.hwaccount.core.base.BaseResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NetworkResponseHandler {
    
    private static final String TAG = "NetworkResponseHandler";
    
    public interface ResponseCallback<T> {
        void onSuccess(T data);
        void onFailure(String errorMsg);
    }
    
    public static <T> void handleResponse(Call<BaseResponse<T>> call, ResponseCallback<T> callback) {
        call.enqueue(new Callback<BaseResponse<T>>() {
            @Override
            public void onResponse(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    BaseResponse<T> body = response.body();
                    if (body.isSuccess()) {
                        callback.onSuccess(body.getData());
                    } else {
                        callback.onFailure(body.getMessage());
                    }
                } else {
                    String errorMsg = "请求失败: " + response.code();
                    if (response.body() != null) {
                        errorMsg += " - " + response.body().getMessage();
                    }
                    callback.onFailure(errorMsg);
                }
            }
            
            @Override
            public void onFailure(Call<BaseResponse<T>> call, Throwable t) {
                Log.e(TAG, "网络请求失败", t);
                callback.onFailure("网络连接失败: " + t.getMessage());
            }
        });
    }
    
    public static <T> void handleSimpleResponse(Call<BaseResponse<T>> call, SimpleResponseCallback callback) {
        handleResponse(call, new ResponseCallback<T>() {
            @Override
            public void onSuccess(T data) {
                callback.onSuccess();
            }
            
            @Override
            public void onFailure(String errorMsg) {
                callback.onFailure(errorMsg);
            }
        });
    }
    
    public interface SimpleResponseCallback {
        void onSuccess();
        void onFailure(String errorMsg);
    }
}